package com.zeildlin.seecode.Controller;

import com.google.code.kaptcha.Producer;
import com.zeildlin.seecode.Service.UserService;
import com.zeildlin.seecode.entity.LoginTicket;
import com.zeildlin.seecode.entity.User;
import com.zeildlin.seecode.util.CommunitConstant;
import com.zeildlin.seecode.util.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController implements CommunitConstant {
    private  static final Logger logger = LoggerFactory.getLogger("LoginController");

    @Autowired
    UserService userService;

    @Autowired
    private Producer producer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @GetMapping("/login")
    public String getLoginPage(){
        return "/site/login";
    }

    @GetMapping("/register")
    public String getRegisterPage(){
        return "/site/register";
    }

    @PostMapping("/register")
    public String register(Model model,User user){
        Map<String,Object> map  = userService.register(user);
        if(map == null || map.isEmpty()){
            model.addAttribute("msg","注册成功，我们已经向您的邮箱发送了一封激活邮件，激活邮件五分钟内有效，请尽快激活");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        }else {
            model.addAttribute("usernameMsg",map.get("usernameMssage"));
            model.addAttribute("passwordMsg",map.get("passwordMssage"));
            model.addAttribute("emailMsg",map.get("EmailMssage"));
            return "/site/register";
        }
    }


    //http://localhost:8080/seecode/activation/101/code
    @GetMapping(path = "/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId")int userid,@PathVariable("code")String code){
        int result = userService.activation(userid,code);
        if(result == ACTIVATION_SUCCESS){
            model.addAttribute("msg","您的账号已经成功激活");
            model.addAttribute("target","/login");
        }else if(result == ACTIVATION_REPEAT){
            model.addAttribute("msg","您的账号不能重复激活,操作无效");
            model.addAttribute("target","/index");

        }else{
            model.addAttribute("msg","您的账号激活失败,链接有误,操作无效");
            model.addAttribute("target","/index");
        }
        return "/site/operate-result";
    }

    @GetMapping(path = "/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        //生成验证码
        String text = producer.createText();
        BufferedImage Image = producer.createImage(text);
        //将验证码存入session
        session.setAttribute("kaptcha",text);

        //将图片输出给浏览器
        response.setContentType("image.png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(Image,"png",os);
        } catch (IOException e) {
            logger.error("相应验证码失败"+e.getMessage());
        }

    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket")String ticket,HttpServletResponse response) {
        userService.logout(ticket);
        Cookie cookie = new Cookie("ticket","");
        cookie.setPath(contextPath);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/login";
    }

    @PostMapping("/login")
    public String login(String username,String password,String code,boolean rememberme,Model model,HttpSession session,HttpServletResponse response){


        String kaptch = (String) session.getAttribute("kaptcha");
        Map<String,Object>map = new HashMap<>();
        if(StringUtils.isBlank(code)||StringUtils.isBlank(kaptch)||!kaptch.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码不正确");
            return "/site/login";
        }
        int expiredSeconds = rememberme ? REMEMBER_EXPIRED_SECONDS:DEFAULT_EXPIRED_SECONDS;
        map = userService.LoginTicket(username,password,expiredSeconds);

        if(map.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            return "redirect:/index";
        }else {
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));

            return "/site/login";
        }
    }

}
